package com.zrl.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrl.project.common.ErrorCode;
import com.zrl.project.common.UserHolder;
import com.zrl.project.exception.BusinessException;
import com.zrl.project.model.VO.messageVO.MessageAndUserInfoVO;
import com.zrl.project.model.entity.Message;
import com.zrl.project.model.entity.User;
import com.zrl.project.service.MessageService;
import com.zrl.project.mapper.MessageMapper;
import com.zrl.project.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 13168
* @description 针对表【message(消息表)】的数据库操作Service实现
* @createDate 2023-04-22 23:04:15
*/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
    implements MessageService{

    @Resource
    private UserService userService;

    @Override
    public List<MessageAndUserInfoVO> getUserMessages() {
        Long id = UserHolder.getUser().getId();
        if (id==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        List<Message> list = lambdaQuery().eq(Message::getReceiverId, id).list();

        return list.stream().map(message -> {
            MessageAndUserInfoVO messageAndUserInfoVO = new MessageAndUserInfoVO();
            BeanUtils.copyProperties(message, messageAndUserInfoVO);
            Long senderId = message.getSenderId();
            User user = userService.lambdaQuery().eq(User::getId, senderId).one();
            messageAndUserInfoVO.setUserAvatar(user.getUserAvatar());
            messageAndUserInfoVO.setUserName(user.getUserName());
            return messageAndUserInfoVO;
        }).collect(Collectors.toList());
    }
}




